package com.example.transformer.service;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.Map;

@Service
public class AnalyzeService {

    @Value("${model.api.url:http://127.0.0.1:5000/analyze}")
    private String modelApiUrl;

    @Value("${model.api.timeout:30000}")
    private int timeout;

    private final RestTemplate restTemplate = new RestTemplate();
    private final ObjectMapper objectMapper = new ObjectMapper();

    /**
     * 调用Python Flask模型API分析代码
     */
    public Map<String, Object> analyzeCode(String code) {
        System.out.println("📨 发送代码到模型API: " + modelApiUrl);
        System.out.println("📝 代码长度: " + code.length() + " 字符");

        try {
            // 设置请求头
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON);
            headers.set("Accept", "application/json");

            // 构建请求体
            Map<String, String> requestBody = new HashMap<>();
            requestBody.put("code", code);

            // 创建HTTP实体
            HttpEntity<Map<String, String>> requestEntity = new HttpEntity<>(requestBody, headers);

            // 发送POST请求
            ResponseEntity<String> response = restTemplate.exchange(
                    modelApiUrl,
                    HttpMethod.POST,
                    requestEntity,
                    String.class
            );

            System.out.println("✅ 收到模型API响应，状态码: " + response.getStatusCode());

            // 解析JSON响应
            return objectMapper.readValue(response.getBody(), Map.class);

        } catch (Exception e) {
            System.err.println("❌ 调用模型API失败: " + e.getMessage());
            Map<String, Object> errorResult = new HashMap<>();
            errorResult.put("error", "无法连接到Python模型服务");
            errorResult.put("details", "请确保Flask服务运行在: " + modelApiUrl);
            errorResult.put("exception", e.getMessage());
            errorResult.put("has_vulnerability", false);
            return errorResult;
        }
    }
}